package com.example.basic.controller;


import com.example.basic.reslut.ResponseResult;
import com.example.basic.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/redis")
public class RedisController {

    private final RedisService redisService;

    @Autowired
    public RedisController(RedisService redisService) {
        this.redisService = redisService;
    }

    @PostMapping("/setnx")
    public ResponseResult<Map<String, Object>> setValue(@RequestParam("key") String key,
                                                        @RequestParam("value") Object value) {
        Boolean success = redisService.setnx(key, value);
        Map<String, Object> redisMap = new HashMap<>();
        if (Boolean.TRUE.equals(success)) {
            redisMap.put(key, value);
        } else {
            redisMap.put("error:", "This key is already present!");
        }
        return ResponseResult.success(redisMap);
    }

    @GetMapping("/get")
    public ResponseResult<Map<String, Object>> getByKey(String key) {
        Object value = redisService.get(key);
        Map<String, Object> redisMap = new HashMap<>();
        redisMap.put(key, value);
        return ResponseResult.success(redisMap);
    }

    @PostMapping("/delete")
    public ResponseResult<Boolean> delete(@RequestParam("key") String key) {
        return ResponseResult.success(redisService.delete(key));
    }
}
